package com.weipai.education.shiro;

import com.weipai.education.dao.UserDao;
import com.weipai.education.model.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author songmengqiang
 * @create 2018-08-20 15:55
 **/
@Component("authRealm")
public class AuthRealm extends AuthorizingRealm {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    //认证.登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        
        User user = userDao.getUserByMobile(usernamePasswordToken.getUsername());

        String mobile = user.getMobile();
        String password = user.getPassword();

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                mobile,
                password,
                ByteSource.Util.bytes(user.getAccountNumber()),
                getName()
        );
        return simpleAuthenticationInfo;
    }
}
